using System.Web.Mvc;
using ETestIT.Core;
using MvcContrib.Pagination;
using SharpArch.Core.PersistenceSupport;
using SharpArch.Core.DomainModel;
using System.Collections.Generic;
using System;
using SharpArch.Web.NHibernate;
using NHibernate.Validator.Engine;
using System.Text;
using SharpArch.Web.CommonValidator;
using SharpArch.Core;

namespace ETestIT.Web.Controllers
{
    [HandleError]
    public class ClientsController : Controller
    {
        public ClientsController(IRepository<Client> clientRepository) {
            Check.Require(clientRepository != null, "clientRepository may not be null");

            this.clientRepository = clientRepository;
        }

        [Transaction]
        public ActionResult Index(int? page) {
            var clients = clientRepository.GetAll().AsPagination(page ??1, 20);
            return View(clients);
        }

        [Transaction]
        public ActionResult Show(int id) {
            Client client = clientRepository.Get(id);
            return View(client);
        }

        public ActionResult Create() {
            ClientFormViewModel viewModel = ClientFormViewModel.CreateClientFormViewModel();
            return View(viewModel);
        }

        [ValidateAntiForgeryToken]
        [Transaction]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(Client client) {
            if (ViewData.ModelState.IsValid && client.IsValid()) {
                clientRepository.SaveOrUpdate(client);

                TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()] = 
					"The client was successfully created.";
                return RedirectToAction("Index");
            }

            ClientFormViewModel viewModel = ClientFormViewModel.CreateClientFormViewModel();
            viewModel.Client = client;
            return View(viewModel);
        }

        [Transaction]
        public ActionResult Edit(int id) {
            ClientFormViewModel viewModel = ClientFormViewModel.CreateClientFormViewModel();
            viewModel.Client = clientRepository.Get(id);
            return View(viewModel);
        }

        [ValidateAntiForgeryToken]
        [Transaction]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(Client client) {
            Client clientToUpdate = clientRepository.Get(client.Id);
            TransferFormValuesTo(clientToUpdate, client);

            if (ViewData.ModelState.IsValid && client.IsValid()) {
                TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()] = 
					"The client was successfully updated.";
                return RedirectToAction("Index");
            }
            else {
                clientRepository.DbContext.RollbackTransaction();

				ClientFormViewModel viewModel = ClientFormViewModel.CreateClientFormViewModel();
				viewModel.Client = client;
				return View(viewModel);
            }
        }

        private void TransferFormValuesTo(Client clientToUpdate, Client clientFromForm) {
			clientToUpdate.Name = clientFromForm.Name;
			clientToUpdate.ContactInformation = clientFromForm.ContactInformation;
			clientToUpdate.TypeOfClient = clientFromForm.TypeOfClient;
        }

        [ValidateAntiForgeryToken]
        [Transaction]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(int id) {
            string resultMessage = "The client was successfully deleted.";
            Client clientToDelete = clientRepository.Get(id);

            if (clientToDelete != null) {
                clientRepository.Delete(clientToDelete);

                try {
                    clientRepository.DbContext.CommitChanges();
                }
                catch {
                    resultMessage = "A problem was encountered preventing the client from being deleted. " +
						"Another item likely depends on this client.";
                    clientRepository.DbContext.RollbackTransaction();
                }
            }
            else {
                resultMessage = "The client could not be found for deletion. It may already have been deleted.";
            }

            TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()] = resultMessage;
            return RedirectToAction("Index");
        }

		/// <summary>
		/// Holds data to be passed to the Client form for creates and edits
		/// </summary>
        public class ClientFormViewModel
        {
            private ClientFormViewModel() { }

			/// <summary>
			/// Creation method for creating the view model. Services may be passed to the creation 
			/// method to instantiate items such as lists for drop down boxes.
			/// </summary>
            public static ClientFormViewModel CreateClientFormViewModel() {
                ClientFormViewModel viewModel = new ClientFormViewModel();
                
                return viewModel;
            }

            public Client Client { get; internal set; }
        }

        private readonly IRepository<Client> clientRepository;
    }
}
